"""自定义的异常处理器"""
from django.http import Http404
from rest_framework.views import exception_handler
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.response import Response
from rest_framework import status
from django.db import DatabaseError
from redis import RedisError
import logging

logger = logging.getLogger('django')


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if isinstance(exc, Http404):
        response.data = {'error': '找不到资源'}

    if isinstance(exc, PermissionDenied):
        response.data = {'error': '权限不足'}

    # if isinstance(exc, ValidationError):
    #     response.data = {'error': '请求数据无效'}
    #     response.status_code = 400
    # 捕获单个数据查询不到的异常
    if response is None:
        view = context['view']

        if isinstance(exc, DatabaseError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response
